﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.IO;
using System.Windows.Media.Imaging;
using System.Windows.Interactivity;
using Microsoft.Expression.Interactivity;
using Microsoft.Expression.Interactivity.Layout;
using FluxJpeg.Core.Encoder;
using FluxJpeg.Core;

namespace FeaturePlusInWeb.Control
{
    public partial class UploadImage : ChildWindow
    {
        /// <summary>
        /// 编码后的图片
        /// </summary>
        public string ImgBase64
        {
            get;
            set;
        }

        /// <summary>
        /// 剪切后的图片的编码
        /// </summary>
        public string CutImgBase64
        {
            get;
            set;
        }

        /// <summary>
        /// 上传图片的原始宽度
        /// </summary>
        public double UpImgWidth
        {
            get;
            set;
        }

        /// <summary>
        /// 上传图片的原始高度
        /// </summary>
        public double UpImgHeight
        {
            get;
            set;
        }

        /// <summary>
        /// 上传后的地址
        /// </summary>
        public string ImgUrl
        {
            get;
            set;
        }

        MouseDragElementBehavior dragBehavior = new MouseDragElementBehavior();

        public UploadImage()
        {
            InitializeComponent();

            rectangle1.Visibility = System.Windows.Visibility.Collapsed;

            dragBehavior.Attach(this.rectangle1);//将本对象加入到可以鼠标拖动的行为对象中去
            dragBehavior.DragFinished += new MouseEventHandler(dragBehavior_DragFinished);

        }

        /// <summary>
        /// 获取控件坐标
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        Point GetControlPoint(object sender)
        {
            var tb = sender as FrameworkElement;

            var gt = tb.TransformToVisual(null);

            Point p = gt.Transform(new Point(0, 0));

            return p;
        }

        void dragBehavior_DragFinished(object sender, MouseEventArgs e)
        {
            MouseDragElementBehavior dragBehavior = sender as MouseDragElementBehavior;
            //矩形的坐标
            Point pReg = GetControlPoint(this.rectangle1);

            //图像的坐标
            Point pImg = GetControlPoint(this.image1);


            double x = pReg.X - pImg.X;

            double y = pReg.Y - pImg.Y;

            double width = this.rectangle1.Width;
            double height = this.rectangle1.Height;

            WriteableBitmap cutImg = cutImage(this.image1, (int)x, (int)y, (int)width, (int)height);

            CutImgBase64 = GetBase64ImageFromWriteableBitmap(cutImg);
        }

        /// <summary>
        /// 老外写的方法：将WriteableBitmap转化为base64位字符串
        /// </summary>
        /// <param name="bitmap"></param>
        /// <returns></returns>
        private string GetBase64ImageFromWriteableBitmap(WriteableBitmap bitmap)
        {
            int width = bitmap.PixelWidth;
            int height = bitmap.PixelHeight;
            int bands = 3;
            byte[][,] raster = new byte[bands][,];

            for (int i = 0; i < bands; i++)
            {
                raster[i] = new byte[width, height];
            }

            for (int row = 0; row < height; row++)
            {
                for (int column = 0; column < width; column++)
                {
                    int pixel = bitmap.Pixels[width * row + column];
                    raster[0][column, row] = (byte)(pixel >> 16);
                    raster[1][column, row] = (byte)(pixel >> 8);
                    raster[2][column, row] = (byte)pixel;
                }
            }

            ColorModel model = new ColorModel { colorspace = ColorSpace.RGB };
            FluxJpeg.Core.Image img = new FluxJpeg.Core.Image(model, raster);
            MemoryStream stream = new MemoryStream();
            JpegEncoder encoder = new JpegEncoder(img, 100, stream);
            encoder.Encode();

            stream.Seek(0, SeekOrigin.Begin);
            byte[] binaryData = new Byte[stream.Length];
            long bytesRead = stream.Read(binaryData, 0, (int)stream.Length);

            string base64String =
                    System.Convert.ToBase64String(binaryData,
                                                  0,
                                                  binaryData.Length);

            return base64String;

        }


        private WriteableBitmap cutImage(System.Windows.Controls.Image img, int x, int y, int width, int height)
        {
            WriteableBitmap bit = new WriteableBitmap(width, height);
            TranslateTransform tran = new TranslateTransform();
            tran.X = -x;
            tran.Y = -y;

            bit.Render(img, tran);
            bit.Invalidate();
            return bit;
        }

        private void OKButton_Click(object sender, RoutedEventArgs e)
        {
            if (openFileDialog == null || openFileDialog.File == null)
            {
                MessageBox.Show("请先从本地选择你要上传的图片或者其他资源。");
                return;
            }

            string fullname = openFileDialog.File.Name;

            string urlAdd = "JPG";

            if (fullname.ToUpper().Contains(".JPG"))
            {
                urlAdd = "JPG";
            }
            else if (fullname.ToUpper().Contains(".GIF"))
            {
                urlAdd = "GIF";
            }
            else if (fullname.ToUpper().Contains(".SWF"))
            {
                urlAdd = "SWF";
            }

            string url = Config.UrlHead + "/featuredplus/upimg.php?ftype=" + urlAdd;
            WebClient webclient = new WebClient();
            webclient.UploadStringCompleted += new UploadStringCompletedEventHandler(webclient_UploadStringCompleted);

            if (checkBox1.IsChecked.HasValue && checkBox1.IsChecked.Value && urlAdd.Equals("JPG"))
            {
                webclient.UploadStringAsync(new Uri(url, UriKind.Absolute), "POST", CutImgBase64);
            }
            else
            {
                if (numericUpDown3.Value != 100)
                {
                    WriteableBitmap cutImg = cutImage(this.image1, 0, 0, (int)this.image1.Width, (int)this.image1.Height);
                    ImgBase64 = GetBase64ImageFromWriteableBitmap(cutImg);
                }

                webclient.UploadStringAsync(new Uri(url, UriKind.Absolute), "POST", ImgBase64);
            }
        }

        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = false;
        }

        OpenFileDialog openFileDialog;

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            openFileDialog = new OpenFileDialog()
            {
                Filter = "支持的格式(*.jpg;*.swf;*.gif)|*.jpg;*.swf;*.gif"
            };

            if (openFileDialog.ShowDialog() == true)//.DialogResult.OK)
            {
                AddFile(openFileDialog.File.OpenRead(), openFileDialog.File.Name);
            }
        }

        void AddFile(FileStream fs, string fileName)
        {
            image1.Width = 618;
            image1.Height = 406;

            slider1.Value = 100;
            numericUpDown3.Value = 100;
            this.image1.Stretch = Stretch.None;

            this.checkBox1.IsChecked = false;

            using (System.IO.Stream fileStream = fs)
            {
                byte[] bytes = new byte[fs.Length];
                fs.Read(bytes, 0, bytes.Length);

                ImgBase64 = Convert.ToBase64String(bytes);

                if (fileName.ToUpper().Contains("JPG"))
                {
                    BitmapImage bitImg = new BitmapImage();
                    bitImg.SetSource(fs);
                    image1.Source = bitImg;
                    this.lblShow.Visibility = System.Windows.Visibility.Collapsed;
                }
                else
                {
                    image1.Source = null;
                    this.lblShow.Visibility = System.Windows.Visibility.Visible;
                    this.lblShow.Content = "文件：" + fileName;
                }
            }
        }

        void webclient_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
        {
            ImgUrl = e.Result;
            this.DialogResult = true;
        }

        private void numericUpDown1_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            //this.rectangle1.Width = numericUpDown1.Value;
        }

        private void numericUpDown2_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            //this.rectangle1.Height = numericUpDown2.Value;
        }

        private void rectangle1_MouseEnter(object sender, MouseEventArgs e)
        {
            
        }

        private void button2_Click(object sender, RoutedEventArgs e)
        {
            this.rectangle1.Width = numericUpDown1.Value;
            this.rectangle1.Height = numericUpDown2.Value;
        }

        private void checkBox1_Checked(object sender, RoutedEventArgs e)
        {
            if (openFileDialog !=null && openFileDialog.File != null)
            {
                string fullname = openFileDialog.File.Name;

                if (fullname.ToUpper().Contains(".JPG"))
                {
                    rectangle1.Visibility = System.Windows.Visibility.Visible;
                }
                else
                {
                    MessageBox.Show("只支持JPG图片切图！");
                    checkBox1.IsChecked = false;
                }
            }
            else
            {
                MessageBox.Show("请先浏览图片再进行操作！");
                checkBox1.IsChecked = false;
            }
        }

        private void checkBox1_Unchecked(object sender, RoutedEventArgs e)
        {
            rectangle1.Visibility = System.Windows.Visibility.Collapsed;
        }

        private void image1_ImageOpened(object sender, RoutedEventArgs e)
        {
            image1.Width = image1.ActualWidth;
            image1.Height = image1.ActualHeight;

            UpImgWidth = image1.ActualWidth;
            UpImgHeight = image1.ActualHeight;


            this.numericUpDown4.Value = this.image1.Width;
            this.numericUpDown5.Value = this.image1.Height;

            this.image1.Stretch = Stretch.Uniform;


        }

        private void slider1_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            if (slider1 != null)
            {
                double changeValue = 1;

                if (slider1.Value > slider1.Maximum / 2)
                {
                    changeValue = 1 + ((slider1.Value - (slider1.Maximum / 2)) / 100);

                    this.image1.Width = UpImgWidth * changeValue;
                    this.image1.Height = UpImgHeight * changeValue;
                }
                else
                {
                    changeValue = (1 - ((slider1.Maximum / 2) - slider1.Value) / 100);

                    this.image1.Width = UpImgWidth * changeValue;
                    this.image1.Height = UpImgHeight * changeValue;
                }

                this.numericUpDown3.Value = 100 * changeValue;

                this.numericUpDown4.Value = this.image1.Width;
                this.numericUpDown5.Value = this.image1.Height;
            }
        }

        private void numericUpDown3_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            if (slider1 != null && numericUpDown3 != null)
            {
                this.slider1.Value = numericUpDown3.Value;
            }
        }

        private void button3_Click(object sender, RoutedEventArgs e)
        {
            this.image1.Width = UpImgWidth;
            this.image1.Height = UpImgHeight;
            slider1.Value = 100;
            numericUpDown3.Value = 100;
        }

        private void numericUpDown4_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            if (numericUpDown4 != null)
            {
                double per = numericUpDown4.Value / UpImgWidth;

                this.slider1.Value = 100 * per;

                this.numericUpDown5.Value = this.numericUpDown5.Value * per;
            }
        }

        private void numericUpDown5_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {

        }
    }
}

